package cn.chiship.framework.docs.biz.controller;

import cn.chiship.framework.docs.biz.pojo.dto.ChunkMultipartFileParam;
import cn.chiship.framework.docs.biz.service.FileResourcesService;
import cn.chiship.framework.docs.biz.service.FileService;
import cn.chiship.sdk.cache.vo.CacheUserVO;
import cn.chiship.sdk.core.annotation.NoParamsSign;
import cn.chiship.sdk.core.annotation.NoVerificationAppIdAndKey;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.framework.common.annotation.LoginUser;

import cn.chiship.framework.docs.core.properties.FileUploadProperties;
import cn.chiship.sdk.framework.multipartFile.Base64ToMultipartFile;
import cn.chiship.sdk.framework.pojo.dto.Base64UploadDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;

/**
 * @author lijian
 */

/**
 * @author lijian
 */
@RequestMapping("/file")
@Api(tags = "文件上传控制器")
@NoVerificationAppIdAndKey
@RestController
public class UploadController {

	@Resource
	FileService fileService;

	@Resource
	FileResourcesService fileResourcesService;

	@Resource
	FileUploadProperties fileUploadProperties;

	/**
	 * 处理文件上传POST请求 将上传的文件存放到服务器内
	 * @param chunk 文件块
	 * @param response 响应
	 * @return 上传响应状态
	 */
	@ApiOperation(value = "文件分片上传")
	@PostMapping("/chunkUpload")
	@NoParamsSign
	public ResponseEntity chunkUploadPost(@ModelAttribute ChunkMultipartFileParam chunk, HttpServletResponse response) {
		return new ResponseEntity(fileService.chunkUploadPost(chunk, response), HttpStatus.OK);
	}

	/**
	 * 处理文件上传GET请求 验证上传的文件块，是否允许浏览器再次发送POST请求（携带二进制文件的请求流，FormData）
	 * @return 文件块
	 */
	@ApiOperation(value = "验证文件分片上传否允许浏览器再次发送POST请求")
	@GetMapping("/chunkUpload")
	@NoParamsSign
	public ResponseEntity chunkUploadGet(@ModelAttribute ChunkMultipartFileParam chunk) {
		return new ResponseEntity(fileService.chunkUploadGet(chunk), HttpStatus.OK);
	}

	@ApiOperation(value = "文件分片上传合并")
	@PostMapping("chunksMerge")
	@NoParamsSign
	public ResponseEntity<BaseResult> chunksMerge(@RequestBody @Valid ChunkMultipartFileParam chunk,
			@ApiIgnore @LoginUser CacheUserVO userVO) {
		String catalogId = chunk.getCatalogId();
		if (StringUtil.isNullOrEmpty(catalogId)) {
			return new ResponseEntity<>(BaseResult.error("缺少参数[catalogId]"), HttpStatus.OK);
		}
		if (StringUtil.isNullOrEmpty(fileUploadProperties.getFilePathByCatalogId(catalogId))) {
			return new ResponseEntity<>(BaseResult.error("文件目录不存在,请核对"), HttpStatus.OK);
		}
		return new ResponseEntity<>(fileService.mergeFile(chunk, userVO), HttpStatus.OK);
	}

	@ApiOperation(value = "文件上传")
	@PostMapping("/upload")
	@NoParamsSign
	public ResponseEntity<BaseResult> upload(HttpServletRequest request, @RequestParam("file") MultipartFile file,
			@ApiIgnore @LoginUser CacheUserVO userVO) throws Exception {
		String catalogId = request.getParameter("catalogId");
		return multipartFileUpload(catalogId, file, userVO);
	}

	@ApiOperation(value = "base64图片上传（body）")
	@PostMapping("/base64UploadNoLogin")
	@NoParamsSign
	public ResponseEntity<BaseResult> base64UploadNoLogin(@RequestBody @Valid Base64UploadDto base64UploadDto)
			throws Exception {
		String catalogId = base64UploadDto.getCatalogId();
		String fileName = base64UploadDto.getFileName();
		MultipartFile file = Base64ToMultipartFile.base64Convert(fileName, base64UploadDto.getBase64());
		return multipartFileUpload(catalogId, file, null);
	}

	@ApiOperation(value = "base64图片上传（body）")
	@PostMapping("/base64Upload")
	@NoParamsSign
	public ResponseEntity<BaseResult> pictureUpload(@RequestBody @Valid Base64UploadDto base64UploadDto,
			@ApiIgnore @LoginUser CacheUserVO userVO) throws Exception {
		String catalogId = base64UploadDto.getCatalogId();
		String fileName = base64UploadDto.getFileName();
		MultipartFile file = Base64ToMultipartFile.base64Convert(fileName, base64UploadDto.getBase64());
		return multipartFileUpload(catalogId, file, userVO);
	}

	@ApiOperation(value = "base64图片上传（Form）")
	@PostMapping("/base64UploadForm")
	@NoParamsSign
	public ResponseEntity<BaseResult> base64UploadForm(HttpServletRequest request, String base64,
			@ApiIgnore @LoginUser CacheUserVO userVO) throws Exception {
		String catalogId = request.getParameter("catalogId");
		String fileName = request.getParameter("fileName");
		if (StringUtil.isNullOrEmpty(catalogId)) {
			return new ResponseEntity<>(BaseResult.error("缺少参数[catalogId]"), HttpStatus.OK);
		}
		if (StringUtil.isNullOrEmpty(fileName)) {
			return new ResponseEntity<>(BaseResult.error("缺少参数[fileName]"), HttpStatus.OK);
		}
		MultipartFile file = Base64ToMultipartFile.base64Convert(fileName, base64);
		return multipartFileUpload(catalogId, file, userVO);
	}

	private ResponseEntity<BaseResult> multipartFileUpload(String catalogId, MultipartFile file, CacheUserVO userVO) {
		BaseResult baseResult = fileResourcesService.uploadFile(file, catalogId, userVO);
		return new ResponseEntity<>(baseResult, HttpStatus.OK);
	}

}
